package shop.core.plugins.wxpay;
import org.springframework.util.ResourceUtils;
import shop.core.common.oscache.SystemManager;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class WXPayConfigImpl extends WXPayConfig {
    private SystemManager systemManager;
    private byte[] certData;
    private static WXPayConfigImpl INSTANCE;

    private WXPayConfigImpl(SystemManager systemManager) throws Exception {
        File file = ResourceUtils.getFile("classpath:apiclient_cert.p12");
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
        this.systemManager=systemManager;
    }

    public static WXPayConfigImpl getInstance(SystemManager systemManager) throws Exception {
        if (INSTANCE == null) {
            synchronized (WXPayConfigImpl.class) {
                if (INSTANCE == null) {
                    INSTANCE = new WXPayConfigImpl(systemManager);
                }
            }
        }
        return INSTANCE;
    }
    //公众号的ID
    public String getAppID() {
        return systemManager.getSystemSetting().getAppid();
    }
    //支付的商户号
    public String getMchID() {
        return systemManager.getSystemSetting().getMchID();
    }
    //商户密钥
    public String getKey() {
        return systemManager.getSystemSetting().getSecret();
    }

    public InputStream getCertStream() {
        ByteArrayInputStream certBis;
        certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }


    public int getHttpConnectTimeoutMs() {
        return 2000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }

    public IWXPayDomain getWXPayDomain() {
        return WXPayDomainSimpleImpl.instance();
    }

    public String getPrimaryDomain() {
        return "api.mch.weixin.qq.com";
    }


    @Override
    public int getReportWorkerNum() {
        return 1;
    }

    @Override
    public int getReportBatchSize() {
        return 2;
    }

    public SystemManager getSystemManager() {
        return systemManager;
    }

    public void setSystemManager(SystemManager systemManager) {
        this.systemManager = systemManager;
    }
}
